package com.sjz.han.industry.fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sjz.han.industry.R;
import com.sjz.han.industry.activites.AllRadiosActivity;
import com.sjz.han.industry.activites.GongLueActivity;
import com.sjz.han.industry.activites.KeFuActivity;
import com.sjz.han.industry.activites.KeFuJsActivity;
import com.sjz.han.industry.activites.LoginActivity;
import com.sjz.han.industry.activites.MyIntegralActivity;
import com.sjz.han.industry.activites.PayActivity;
import com.sjz.han.industry.activites.ProductJsActivity;
import com.sjz.han.industry.activites.RegistActivity;
import com.sjz.han.industry.activites.WaitSettlementMemberActivity;
import com.sjz.han.industry.adapters.MainTwjsAdapter;
import com.sjz.han.industry.base.AppConfig;
import com.sjz.han.industry.base.BaseFragment;
import com.sjz.han.industry.entities.HomeEntity;
import com.sjz.han.industry.entities.LoignEntity;
import com.sjz.han.industry.internetmanage.ReqestUrl;
import com.sjz.han.industry.utils.JsonUtils;
import com.sjz.han.industry.utils.PicUtils;
import com.sjz.han.industry.utils.ToastUtils;
import com.sjz.han.industry.weight.CustomViewPager;
import com.sjz.han.industry.weight.MarqueeView;
import com.sjz.han.industry.wxapi.Util;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener{

    private CustomViewPager home_banner;
    private ArrayList<String> imagUrls = new ArrayList<>();
    private List<HomeEntity.HomeData.BannerBean> bannerBeanList=new ArrayList<>();

    private MarqueeView home_notice_marquee;
    private List<String> pmdStringList = new ArrayList<>();
    private List<HomeEntity.HomeData.NoticeBean> noticeBeans=new ArrayList<>();
    private TextView home_morenotice_tv;

    private RecyclerView main_twjs_recy;
    private MainTwjsAdapter twjsAdapter;
    private String myJf="";//我的积分

    private LinearLayout home_WDJF_ll,home_Share_ll,home_GONGLUE_ll,home_KEFU_ll;//我的积分
    private TextView home_JF_TV;//积分

    private TextView main_notice_tv;//主页通知
    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        home_banner = (CustomViewPager) getView().findViewById(R.id.home_banner);
        home_notice_marquee=(MarqueeView)getView().findViewById(R.id.home_notice_marquee);
        pmdStringList=new ArrayList<>();
        home_morenotice_tv=(TextView)getView().findViewById(R.id.home_morenotice_tv);

        main_twjs_recy=(RecyclerView)getView().findViewById(R.id.main_twjs_recy);
        main_twjs_recy.setLayoutManager(new LinearLayoutManager(activity));
        twjsAdapter=new MainTwjsAdapter(activity);
        main_twjs_recy.setAdapter(twjsAdapter);


        home_JF_TV=(TextView)getView().findViewById(R.id.home_JF_TV);

        home_WDJF_ll=(LinearLayout)getView().findViewById(R.id.home_WDJF_ll);
        home_Share_ll=(LinearLayout)getView().findViewById(R.id.home_Share_ll);
        home_GONGLUE_ll=(LinearLayout)getView().findViewById(R.id.home_GONGLUE_ll);
        home_KEFU_ll=(LinearLayout)getView().findViewById(R.id.home_KEFU_ll);

        main_notice_tv=(TextView)getView().findViewById(R.id.main_notice_tv);

    }

    @Override
    protected void initDatas() {
       getHomeMsg();
    }

    @Override
    protected void setLisener() {
        home_WDJF_ll.setOnClickListener(this);
        home_notice_marquee.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
//                startActivity(new Intent(activity, DY_NoticeDetailActivity.class).putExtra("id",pmdList.get(position).id));
            }
        });
        home_GONGLUE_ll.setOnClickListener(this);
        home_KEFU_ll.setOnClickListener(this);
        home_Share_ll.setOnClickListener(this);
        home_morenotice_tv.setOnClickListener(this);
        main_notice_tv.setOnClickListener(this);
    }

    @Override
    protected void onRetry() {
       getHomeMsg();
    }

    @Override
    public void onClick(View v) {
          switch (v.getId()){
              case R.id.home_WDJF_ll://我的积分
                  startActivity(new Intent(activity, MyIntegralActivity.class).putExtra("myjf",myJf));
                  break;
              case R.id.home_GONGLUE_ll://攻略
                  startActivity(new Intent(activity, GongLueActivity.class));
                  break;
              case R.id.home_KEFU_ll://客服
                  startActivity(new Intent(activity, KeFuJsActivity.class));
                  break;
              case R.id.home_Share_ll://分享
                  wechatShare(0);
                  break;
              case R.id.home_morenotice_tv:
                  startActivity(new Intent(activity, AllRadiosActivity.class).putExtra("noticeBeans",(Serializable) noticeBeans));
                  break;
              case R.id.main_notice_tv://带结算会员列表
                  startActivity(new Intent(activity, WaitSettlementMemberActivity.class));
                  break;
          }
    }

    @Override
    public void onResume() {
        super.onResume();
        if("5".equals(shareUtils.getLevel())){//如果是C2才执行
            getYuQi();
        }

    }

        public void getHomeMsg(){
        showLoading();
        OkHttpUtils
                .post()
                .url(ReqestUrl.HOME_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
                showFaild();
            }
            @Override
            public void onResponse(String response, int id) {
                showSuccess();
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    HomeEntity entity= JsonUtils.getObject(response,HomeEntity.class);
                    if(entity!=null&&entity.code==0){
                        if(entity.data.uplist!=null&&entity.data.uplist.size()>0){//轮播图
                            initBannerSwitch(entity.data.uplist);
                            bannerBeanList.addAll(entity.data.uplist);
                        }
                        myJf=entity.data.money;
                        home_JF_TV.setText(entity.data.money);//积分
                        if(entity.data.downlist!=null&&entity.data.downlist.size()>0){//图文介绍
                            twjsAdapter.setAdapterDatas(entity.data.downlist);
                        }
                        if(entity.data.CRadios!=null&&entity.data.CRadios.size()>0){//广播
                            noticeBeans.addAll(entity.data.CRadios);
                           for(int i=0;i<noticeBeans.size();i++){
                               pmdStringList.add(noticeBeans.get(i).content);
                               home_notice_marquee.startWithList(pmdStringList);
                           }
                        }
                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }
    public void getYuQi(){
        OkHttpUtils
                .post()
                .url(ReqestUrl.SFYYQ_NOTICE_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }
            @Override
            public void onResponse(String response, int id) {

                if(ReqestUrl.rebacRequestJson(response)!=null){
                    LoignEntity entity= JsonUtils.getObject(response,LoignEntity.class);
                    if(entity!=null&&entity.code==0){
                        //        0 没有逾期结算 1  有逾期结算
                        if(entity.code==0){
                            if("1".equals(entity.data.flag)){
                                main_notice_tv.setVisibility(View.VISIBLE);
                            }else{
                                main_notice_tv.setVisibility(View.GONE);
                            }
                        } else if(entity.code==301){
                            startActivity(new Intent(activity,LoginActivity.class));
                            activity.finish();
                        }
                    }
                }
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }




    /**
     * 初始化轮播图
     */
    public void initBannerSwitch(List<HomeEntity.HomeData.BannerBean> datas) {
        if(imagUrls.size()>0){
            imagUrls.clear();
        }
        for(int i=0;i<datas.size();i++){
            imagUrls.add(ReqestUrl.BASE+datas.get(i).imgUrl);
        }

        home_banner.setImageResources(imagUrls, mAdCycleViewListener);
    }

    private CustomViewPager.ImageCycleViewListener mAdCycleViewListener = new CustomViewPager.ImageCycleViewListener() {
        @Override
        public void onImageClick(int position, View imageView) {
            // TODO 单击图片处理事件
            int curPos = home_banner.getCurPos();
            String url = bannerBeanList.get(curPos).id;
            if(!TextUtils.isEmpty(url)){
                startActivity(new Intent(activity, ProductJsActivity.class).putExtra("imagId",url));
            }
        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {
            PicUtils.showImgRoundedtwo(activity, imageView, imageURL);

        }
    };
    //===========================微信分享======================================
    private String shareUrl="";
    private String shareTitle="INDUSTRY";
    private String shareSummary="奔向财富自由之路！";
    private void wechatShare(int flag) {//0微信，1朋友圈
        shareUrl=ReqestUrl.BASEH5+"/frontHtml/yindao.php?a="+shareUtils.getYQM();
        IWXAPI api = WXAPIFactory.createWXAPI(mContext, AppConfig.app_id);
        api.registerApp(AppConfig.app_id);
        if (!api.isWXAppInstalled()) {
            Toast.makeText(mContext, "您还未安装微信客户端",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = shareTitle;
        msg.description = shareSummary;
        //这里替换一张自己工程里的图片资源
        Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }
}
